﻿using Sidvall.UI.Dialogs;
using Sidvall.UI.ViewModels;
using System;
using System.Threading.Tasks;

namespace Sidvall.UI.Uwp.Dialogs
{
    public sealed partial class WebDialog
    {
        #region Public Members

        #region ViewModel

        public WebControlViewModel ViewModel
        {
            get
            {
                return this.DataContext as WebControlViewModel;
            }
            set
            {
                var oldValue = this.DataContext as WebControlViewModel;
                this.DataContext = value;
            }
        }

        #endregion

        #region InitializeContext

        public void InitializeContext(WebDialogContext context)
        {
            if (context == null)
                throw new System.ArgumentNullException("context");
            var item = new WebControlViewModel()
            {
            };
            this.ViewModel = item;
            if (!string.IsNullOrWhiteSpace(context.RequestMessage?.WebAddress))
            {
                var requestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, new System.Uri(context.RequestMessage.WebAddress));
                if (context.RequestMessage.Headers != null)
                {
                    foreach (var header in context.RequestMessage.Headers)
                        requestMessage.Headers.Add(header.Name, header.Value);
                }
                this.WebView.NavigateWithHttpRequestMessage(requestMessage);
            }
            else if (!string.IsNullOrWhiteSpace(context.HtmlText))
            {
                this.WebView.NavigateToString(context.HtmlText);
            }
        }

        #endregion
        #region ShowAsync

        public async Task ShowAsync(WebDialogContext context, object owner)
        {
            var page = owner as Windows.UI.Xaml.Controls.Page;
            ControlManager.SetHeight(this, page.ActualHeight, null);
            ControlManager.SetWidth(this, page.ActualWidth, 1200);
            InitializeContext(context);
            this.Title = context.Title;
            await ShowAsync();
        }

        #endregion

        #endregion
        #region Constructors

        public WebDialog()
        {
            this.InitializeComponent();
        }

        #endregion
    }
}
